//
//  MCChooseImageView.swift
//  StoreManage
//
//  Created by MC on 2018/9/11.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

/**
 * 选择图片 相册/相机
 *
 */

typealias MCChooseImageViewClosure = (UIImage) -> Void

class MCChooseImageView: UIView {

    var closure : MCChooseImageViewClosure?
    
    
    public var isNeedEditImage = false
    public var superViewController : UIViewController? = (UIApplication.shared.keyWindow?.rootViewController)
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    
        self.addSubview(whiteView)
        whiteView.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(193)
        }
        
        whiteView.addSubview(cancelButton)
        cancelButton.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.bottom.equalTo(0)
            make.height.equalTo(50)
        }
        
        whiteView.addSubview(lineOneView)
        lineOneView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(whiteView)
            make.height.equalTo(1)
            make.bottom.equalTo(cancelButton.snp.top)
        }
        
        whiteView.addSubview(photoButton)
        photoButton.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.bottom.equalTo(lineOneView.snp.top)
            make.height.equalTo(50)
        }
        
        whiteView.addSubview(lineTwoView)
        lineTwoView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(whiteView)
            make.height.equalTo(1)
            make.bottom.equalTo(photoButton.snp.top)
        }


        whiteView.addSubview(libraryButton)
        libraryButton.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.bottom.equalTo(lineTwoView.snp.top)
            make.height.equalTo(50)
        }

        whiteView.addSubview(lineThreeView)
        lineThreeView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(whiteView)
            make.height.equalTo(1)
            make.bottom.equalTo(libraryButton.snp.top)
        }


        whiteView.addSubview(titleLabel)
        titleLabel.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.bottom.equalTo(lineThreeView.snp.top)
            make.height.equalTo(40)
        }

        self.addSubview(grayView)
        grayView.snp.remakeConstraints { (make) ->Void in
            make.left.right.top.equalTo(self)
            make.bottom.equalTo(whiteView.snp.top)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func dismissSelf() {
        self.removeFromSuperview()
    }
    
    @objc func libraryButtonClicked() {
        dismissSelf()
        libraryClicked()
    }

    @objc func photoButtonClicked() {
        dismissSelf()
        cameraClicked()
    }
    
    // 图库
    func libraryClicked() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            let vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = isNeedEditImage
            vc.sourceType = UIImagePickerControllerSourceType.photoLibrary
            superViewController?.present(vc, animated: true, completion: { })
        }
    }
    
    func cameraClicked() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
            
            let availableMeidatypes : NSArray = UIImagePickerController.availableMediaTypes(for: UIImagePickerControllerSourceType.camera)! as NSArray
            
            var canTakePicture = false
            
            for mediaType in availableMeidatypes {
                
                let str = mediaType as? String
                
                if str == String(kUTTypeImage) {
                    canTakePicture = true
                    break
                }
            }
            
            guard canTakePicture else {
                return
            }
            
            let vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = isNeedEditImage
            vc.sourceType = UIImagePickerControllerSourceType.camera
            vc.mediaTypes = NSArray(object: String(kUTTypeImage)) as! [String]
            superViewController?.present(vc, animated: true, completion: { })
            
        }
    }

    lazy var grayView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.init(white: 0, alpha: 0.4)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(dismissSelf))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var lineOneView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.MCGray_light
        return view
    }()

    lazy var lineTwoView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.MCGray_light
        return view
    }()

    lazy var lineThreeView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.MCGray_light
        return view
    }()

    
    
    lazy var whiteView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        return view
    }()
    
    lazy var titleLabel: MCLabel = {
        let label = MCLabel()
        label.font = MCFont(13)
        label.textColor = UIColor.MCGray_middle
        label.text = "选择上传图片的方式"
        label.textAlignment = NSTextAlignment.center
        return label
    }()
    
    lazy var libraryButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(14)
        button.setTitle("相册", for: .normal)
        button.setTitleColor(UIColor.MCWords, for: .normal)
        button.addTarget(self, action: #selector(libraryButtonClicked), for: .touchUpInside)
        return button
    }()
    
    lazy var photoButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(14)
        button.setTitle("拍照", for: .normal)
        button.setTitleColor(UIColor.MCWords, for: .normal)
        button.addTarget(self, action: #selector(photoButtonClicked), for: .touchUpInside)
        return button
    }()
    
    lazy var cancelButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(14)
        button.setTitle("取消", for: .normal)
        button.setTitleColor(UIColor.MCRed, for: .normal)
        button.addTarget(self, action: #selector(dismissSelf), for: .touchUpInside)
        return button
    }()
}

extension MCChooseImageView: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let mediaType = info[UIImagePickerControllerMediaType] as! String
        
        if mediaType == String(kUTTypeImage) {
            
            var image : UIImage?
            
            
            if isNeedEditImage {
                let originalImage : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
                
                let rect = info[UIImagePickerControllerCropRect] as! CGRect
                
                image = originalImage.MCImageCrop(toRect: rect)
            } else {
                image = info[UIImagePickerControllerOriginalImage] as? UIImage
            }
            
            
            picker.dismiss(animated: true) {
                self.closure?(image!)
            }
        }
    }
}

